package com.norriekoelle.virtualsensors.kinect;


import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.norriekoelle.virtualsensors.kinect.R;
import com.norriekoelle.virtualsensors.kinect.Connection.BluetoothClient;
import com.norriekoelle.virtualsensors.kinect.Connection.WifiClient;
import com.norriekoelle.virtualsensors.kinect.hotspots.ClientActivity;

public class ConnectionManager {

	private static final String LOG = "BookshelfConnMan";
	WifiClient wifiClient = null;
	BluetoothClient btClient = null;
	ClientActivity activity;
	enum MODES {WIFI, BLUETOOTH, OFFLINE}
	enum DIALOG_ACTION {CAMERA, GALLERY, BOOKS}
	int currentApp = -1;
	MODES mode = MODES.WIFI;
	boolean dialogOpen = false;
	private Builder d;

	
	public ConnectionManager(ClientActivity c){
		activity = c;
		
		//wifi first
		wifiClient = new WifiClient(activity, this);
		if(!wifiClient.wifiAvailable){
			/*AlertDialog.Builder a = new AlertDialog.Builder(activity);
			//a.setMessage("Please connect to a wifi network and try again.")
    		a.setMessage("Wifi unavailable. Bluetooth mode on.")
					.setCancelable(false)
					.setNeutralButton("OK",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int id) {
								dialog.cancel();
								//context.finish();
							}
					});
			a.create();
			a.show();*/
			
			wifiClient = null;
			
			//else bt
			btClient = new BluetoothClient(activity, this);
			mode = MODES.BLUETOOTH;
		}
			
	}
	
	
	public void send(String message){
		switch(mode){
		case WIFI:
			wifiClient.sendUDPMessage("", message);
			break;
			
		case BLUETOOTH:
			btClient.sendMessage(message);
			break;
		}
	}
	
	public void connected(){
		switch(mode){
		case WIFI:
			wifiClient.connected();
			break;
			
		case BLUETOOTH:
			//
			break;
		}
		
		message("ack");
		send("ack\n");
	}
	
	public void reconnect(){
		switch(mode){
		case WIFI:
			wifiClient.reconnect();
			break;
			
		case BLUETOOTH:
			//
			break;
		}
	}
	
	public void handleMessage(String serverMessage){
		Log.d(LOG, serverMessage);
		CommandInterface.commands c = CommandInterface.handleKinectMessage(serverMessage);
		
		switch(c){
		case EXIT:
				
				noHotspotsUI();
				reconnect();				
				break;
		case CONNECT:
				Log.d(LOG, c.toString());
	    		connected();
	    		break;
		case ACK:
				//send device ID with ip address, updated in AndroidClient
				//send("add " );//+ getLocalIpAddress());
				//send("hotspot\n");
				
				/*Display ID on screen
				 * context.runOnUiThread(new Runnable(){
						@Override
						public void run() {
							TextView idView = (TextView)context.findViewById(R.id.clientID);
							idView.setText(ID +" : (no users)");
						}
				});*/
				break;
	    /* *** */
		case TRACKING_ON:			
				//start logging accel
				//AndroidClient.doLog = true;
//				activity.runOnUiThread(new Runnable(){
//					@Override
//					public void run() {
//					 	Button b= (Button)activity.findViewById(R.id.hotButton);
//					 	b.setEnabled(true);
//					 	b.setClickable(true);
//					}
//				 });
				break;
		case TRACKING_OFF:
				//stop logging accel
				//AndroidClient.doLog = false; 
				/* 
				 * Disable the hotspot button
				 * context.runOnUiThread(new Runnable(){
					@Override
					public void run() {
					 	Button b= (Button)context.findViewById(R.id.hotButton);
					 	b.setEnabled(false);
					 	b.setClickable(false);
					}
				 });*/
			
				break;
		/*case NEW_USER:
				//parse ID
				String num = serverMessage.substring(serverMessage.indexOf("user ")+5,
													 serverMessage.indexOf("user ")+6);
				int got_userid = Integer.valueOf(num);
	
				//New: assigned id
				if(serverMessage.toLowerCase().contains("new")){
					userID = got_userid;				
					/* Update on screen
					 * context.runOnUiThread(new Runnable(){
						public void run() {
							TextView idView = (TextView)context.findViewById(R.id.clientID);
							idView.setText(ID +" : User " + userID);
						}
					});*
				}	
				break;
		case LOST_USER:
				num = serverMessage.substring(serverMessage.indexOf("user ")+5,
						 serverMessage.indexOf("user ")+6);
				got_userid = Integer.valueOf(num);
				
				if(userID == got_userid){
					userID = -1;
					/*Update on screen
					 * context.runOnUiThread(new Runnable(){
						@Override
						public void run() {
							//TextView idView = (TextView)context.findViewById(R.id.clientID);
							//idView.setText(ID +" : (lost user)");
						}
					 });*
				}
				break;*/
		/* *** */
		case LOG_ON:
				message("Log on");
				activity.doLog(true);
				break;
		case LOG_OFF:
				this.message("Log off");
				activity.doLog(false);
				break;
		case SWIPE_L:
				activity.handleMessage("Swipe left");
				break;
		case SWIPE_R:
					activity.handleMessage("Swipe right");
				break;
		case PUSH:
				activity.handleMessage("push");

				break;
		case CLICK:
				activity.handleMessage("click");

				break;
		case CIRCLE:
				activity.handleMessage("circle");

				break;	
		/* *** */
		case HOTSPOT:
    			activity.handleMessage(serverMessage);
			break;
			/* *** */

		default:
			break;
		}
	}
	
	public void noHotspotsUI(){
		activity.runOnUiThread(new Runnable(){
			@Override
			public void run() {
				TextView hid = (TextView)activity.findViewById(R.id.hotID);
				TextView tag = (TextView)activity.findViewById(R.id.hotText);
				Button bh = (Button)activity.findViewById(R.id.hotButton);
				Button bi = (Button)activity.findViewById(R.id.launcher);
				
				hid.setText("");
				tag.setText("None here!");
				if(dialogOpen)
					d = null;
				bi.setVisibility(Button.INVISIBLE);
				bh.setVisibility(Button.VISIBLE);
				
				if(currentApp!=-1){
					closeApp(currentApp);
					currentApp = -1;							
				}	
			}
		});
	}
	
	public void createAndShowDialog(String title, String message, DIALOG_ACTION action){
		
		if(dialogOpen)
			return;
		
		d = new AlertDialog.Builder(activity);
		final DIALOG_ACTION a = action;
		d.setTitle(title);
		d.setMessage(message)
				.setCancelable(true)
				.setPositiveButton("YES", 
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int id) {
						if(!launchApp(a)) dialog.cancel();

						dialogOpen = false;
						//context.finish();
					}
			})
				.setNeutralButton("NO",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int id) {
							dialog.cancel();	
							dialogOpen = false;
							//context.finish();
						}
				});
		d.create();
		d.show();
		dialogOpen = true;
	}
	
	public boolean launchApp(DIALOG_ACTION app){
		if(currentApp == app.ordinal())
			return false;
		
		Intent i = null;		
		switch(app){
		case CAMERA:
			i = new Intent("android.media.action.IMAGE_CAPTURE");
			currentApp = DIALOG_ACTION.CAMERA.ordinal();
			break;
		case GALLERY: 
			i = new Intent(Intent.ACTION_PICK, 
					android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
			currentApp = DIALOG_ACTION.GALLERY.ordinal();
			break;
		case BOOKS: 
			i = new Intent();
			i.setClassName("com.norriekoelle.virtualsensors", "com.norriekoelle.virtualsensors.android.virtualbookshelf.BookshelfActivity");
			i.putExtra("collection", 2);
			currentApp = DIALOG_ACTION.BOOKS.ordinal();
			break;
		default:
			break;
		}						
		if(i!=null){
			try{activity.startActivityForResult(i, currentApp);}
			catch(Exception e){AlertDialog.Builder a = new AlertDialog.Builder(activity); a.setMessage("Application not installed: "  + i.getPackage());}
			return true;
		}
		return false;
	}
	
	public boolean closeApp(int app){
			try{activity.finishActivity(currentApp);}
			catch(Exception e){return false;}
			return true;
	}
	
	public void close(){
		message("Closing connection...");
		
		if(wifiClient!=null){
			wifiClient.exiting = true;
			wifiClient.closeServer();
		}
		if(btClient!=null)
			btClient.closeServer();
	}

	/**
	 * Log a message
	 * @param message
	 */
    public void message(String message){
    	Log.d("AndroidClient",message);
    }
	
}
